import Cesium, { TaskProcessor } from '../Ces/Cesium'

class WeTaskProcessorPool {
  private taskProcessors: TaskProcessor[] = []
  private wasmBinary: ArrayBuffer

  async getTaskProcessor(i: number = 0) {
    if (!this.taskProcessors[i]) {
      if (!this.wasmBinary) {
        this.wasmBinary = await Cesium.Resource.fetchArrayBuffer(Cesium.buildModuleUrl('we-assets/we.wasm'))
      }
      this.taskProcessors[i] = new Cesium.TaskProcessor('../we-assets/Workers/weWorkers.js')
      await this.taskProcessors[i].scheduleTask({
        webAssemblyConfig: {
          wasmBinary: this.wasmBinary
        }
      })
    }

    return this.taskProcessors[i]
  }

  isDestroyed() {
    return false
  }

  destroy() {
    this.taskProcessors.forEach(e => e.destroy())
    this.taskProcessors.length = 0
    return Cesium.destroyObject(this)
  }
}

export default WeTaskProcessorPool
